<?php

namespace app\admin\model;

use app\api\controller\Contract;
use app\common\library\Acsign;
use app\common\model\Authentication;
use EasyWeChat\Factory;
use think\Db;
use think\Model;
use traits\model\SoftDelete;

class Order extends Model
{
    use SoftDelete;

    // 表名
    protected $name = 'order';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = [
        'status_text'
    ];

    public function getStatusList()
    {
        return ['1' => __('Status 1'), '2' => __('Status 2')];
    }
    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }
    public function good()
    {
        return $this->belongsTo('Goods','good_id','id');
    }
    public function user()
    {
        return $this->belongsTo('User','user_id','id')->field('id,nickname,mobile,openid,avatar,money');
    }
    public function seller()
    {
        return $this->belongsTo('User','seller_id','id')->field('id,nickname,mobile,openid,avatar,money');
    }

    /**
     * 直接下单生成订单
     */
    public function add($data,$user_id,$trade_no,$transaction_id)
    {
        //服务费
        $service = $data->total_price * $data->buyer_commission;
        if(isset($data->coupon_id) && $data->coupon_id > 0){
            \db('user_coupon')->where('id',$data->coupon_id)->update([
                'status' => 1
            ]);
            //服务费-优惠券
            $service = $data->total_price * $data->buyer_commission - $data->coupon_price;
            if($service <= 0){
                $service = 0;
            }
        }
        $order_id = \db('order')->insertGetId([
            'user_id' => $data->user_id,
            'trade_no' => $trade_no,
            'transaction_id' => $transaction_id,
            'seller_id' => $data->seller_id,
            'good_id' => $data->good_id,
            'title' => $data->title,
            'image' => $data->image,
            'name' => $data->buyer_name,
            'phone' => $data->buyer_phone,
            'seller_name' => $data->seller_name,
            'seller_phone' => $data->seller_phone,
            'price' => $data->price,
            'total_price' => $data->total_price,
            'earnest' => $data->earnest,
            'buyer_commission' => $data->buyer_commission,
            'service' => $service,
            'coupon_id' => isset($data->coupon_id) ? $data->coupon_id : null,
            'coupon_price' => isset($data->coupon_price) ? $data->coupon_price : 0,
            'status' => 1,
            'buyer_status' => 1,
            'seller_status' => 1,
            'is_seller' => $data->is_seller,
            'selltime' => $data->selltime,
            'pay_time' => date('Y-m-d H:i:s',time()),
            'createtime' => date('Y-m-d H:i:s',time()),
            'updatetime' => time()
        ]);
        if($order_id){
            \db('goods')->where('id',$data->good_id)->update([
                'order_id' => $order_id,
                'status' => 3
            ]);
            db('explosive_goods')->where(['goods_id'=>$data->good_id])->update([
                'status' => 3
            ]);
            db('overbalance_goods')->where(['goods_id'=>$data->good_id])->update([
                'status' => 3
            ]);
            db('recommend_goods')->where(['goods_id'=>$data->good_id])->update([
                'status' => 3
            ]);
            //上传待签署文件
            $this->index($order_id);
            return true;
        }
        return false;
    }
    /**
     * 购物车生成订单
     */
    public function adds($data,$user_id,$total_money,$trade_no,$transaction_id)
    {
        foreach ($data as $v){
            //服务费
            $service = $v->total_price * $v->buyer_commission;
            if(isset($v->coupon_id) && $v->coupon_id > 0){
                \db('user_coupon')->where('id',$v->coupon_id)->update([
                    'status' => 1
                ]);
                //服务费-优惠券
                $service = $v->total_price * $v->buyer_commission - $v->coupon_price;
                if($service <= 0){
                    $service = 0;
                }
            }
            $order_id = \db('order')->insertGetId([
                'user_id' => $user_id,
                'trade_no' => $trade_no,
                'transaction_id' => $transaction_id,
                'seller_id' => $v->seller_id,
                'good_id' => $v->good_id,
                'title' => $v->title,
                'image' => $v->image,
                'name' => $v->name,
                'phone' => $v->phone,
                'price' => $v->total_price,
                'total_price' => $total_money,
                'earnest' => $v->earnest,
                'buyer_commission' => $v->buyer_commission,
                'service' => $service,
                'coupon_id' => isset($v->coupon_id) ? $v->coupon_id : null,
                'coupon_price' => isset($v->coupon_price) ? $v->coupon_price : 0,
                'status' => 1,
                'buyer_status' => 1,
                'seller_status' => 1,
                'pay_time' => date('Y-m-d H:i:s',time()),
                'createtime' => date('Y-m-d H:i:s',time()),
                'updatetime' => time()
            ]);
            if($order_id){
                \db('goods')->where('id',$v->good_id)->update([
                    'order_id' => $order_id,
                    'status' => 3
                ]);
                db('explosive_goods')->where(['goods_id'=>$v->good_id])->update([
                    'status' => 3
                ]);
                db('overbalance_goods')->where(['goods_id'=>$v->good_id])->update([
                    'status' => 3
                ]);
                db('recommend_goods')->where(['goods_id'=>$v->good_id])->update([
                    'status' => 3
                ]);
                db('cart')->where(['good_id'=>$v->good_id])->delete();
            }
        }
        return true;
    }
    /**
     * 退还押金
     */
    public function earnestReturn($order,$dedit)
    {
        //如果未发货，扣除卖家违约金给买家
        //如果已发货，扣除买家违约金给卖家
        if($order['deliver_status'] == 1){
            $this->buyearnest($order,0);
            $this->sellearnest($order,$dedit);
            //发放违约金给买家
            $userid = $order['user_id'];
        }else{
            $this->buyearnest($order,$dedit);
            $this->sellearnest($order,0);
            //发放违约金给卖家
            $userid = $order['seller_id'];
        }
        \app\common\model\User::money($dedit,$userid,'违约金');
    }
    /**
     * 退还买家定金 定金-服务费
     */
    public function buyearnest($order,$dedit)
    {
        if($order['is_seller'] == 1){//卖出
            $totalFee = $order['total_price'];
            $refundFee = $order['earnest'] - $order['service'];
            $transaction_id = $order['transaction_id'];
        }else{
            $totalFee = $order['good']['earnest_money'] + $order['good']['exposure_fee'] + $order['good']['referral_fee'] + $order['good']['premium_fee'];
            $refundFee = $order['good']['earnest_money'] - $order['good']['service'];
            $transaction_id = $order['good']['transaction_id'];
        }
        $refundFee = bcsub($refundFee,$dedit,2);
        $config = $this->config();
        $app = Factory::payment($config);
        $refundNumber = 'tk'.time().rand(100,999);
        // 参数分别为：微信订单号、商户退款单号、订单金额、退款金额、其他参数
        $result = $app->refund->byTransactionId($transaction_id, $refundNumber, intval($totalFee * 100), intval($refundFee * 100), [
            // 可在此处传入其他参数，详细参数见微信支付文档
            'refund_desc' => '退还定金',
        ]);
    }
    /**
     * 退还卖家保证金 保证金-服务费
     */
    public function sellearnest($order,$dedit)
    {
        if($order['is_seller'] == 2){//买入
            $totalFee = $order['total_price'];
            $refundFee = $order['earnest'] - $order['service'];
            $transaction_id = $order['transaction_id'];
        }else{
            $totalFee = $order['good']['earnest_money'] + $order['good']['exposure_fee'] + $order['good']['referral_fee'] + $order['good']['premium_fee'];
            $refundFee = $order['good']['earnest_money'] - $order['good']['service'];
            $transaction_id = $order['good']['transaction_id'];
        }
        $refundFee = bcsub($refundFee,$dedit,2);
        $config = $this->config();
        $app = Factory::payment($config);
        $refundNumber = 'tk'.time().rand(1000,9999);
        // 参数分别为：微信订单号、商户退款单号、订单金额、退款金额、其他参数
        $result = $app->refund->byTransactionId($transaction_id, $refundNumber, $totalFee * 100, $refundFee * 100, [
            // 可在此处传入其他参数，详细参数见微信支付文档
            'refund_desc' => '退还保证金',
        ]);
    }
    /**
     * 配置
     */
    public function config()
    {
        //获取插件
        $config = get_addon_config('epay');
        $config = [
            // 必要配置
            'app_id' => $config['wechat']['miniapp_id'],
            'mch_id' => $config['wechat']['mch_id'],
            'key' => $config['wechat']['key'],   // API v2 密钥 (注意: 是v2密钥 是v2密钥 是v2密钥)
            // 如需使用敏感接口（如退款、发送红包等）需要配置 API 证书路径(登录商户平台下载 API 证书)
            'cert_path'          => ROOT_PATH.'addons/epay/certs/apiclient_cert.pem', // XXX: 绝对路径！！！！
            'key_path'           => ROOT_PATH.'addons/epay/certs/apiclient_key.pem',      // XXX: 绝对路径！！！！
            'notify_url' => '',     // 你也可以在下单时单独设置来想覆盖它
        ];
        return $config;
    }

    /**
     * 上传合同/上传待签署文件
     */
    public function index($order_id)
    {
        $order = db('order')->where('id',$order_id)->find();
        $buyer = Authentication::where('user_id',$order['user_id'])->find();
        $seller = Authentication::where('user_id',$order['seller_id'])->find();
        $goods = \db('goods')->where('id',$order['good_id'])->find();
        //1卖出 2买入
        if($order['is_seller'] == 1){
            $buyer_address = '';
            $seller_address = $goods['place_origin'];
        }else{
            $buyer_address = $goods['place_origin'];
            $seller_address = '';
        }
        $asignInstance = new Acsign();
//        $re = $asignInstance->getContract('TN115F0853CBDE4C37AF1AEC9E61CF175D');
//        print_r($re);die;
        //上传待签署文件（使用模板的）
        $contractNo = "HT".time().rand(100,999);
        $contract = array();
        $contract["contractName"] = "买卖合同";
        $contract["contractNo"] = $contractNo;
        $contract["signOrder"] = 1;
        $contract["validityTime"] = "30";
        // 爱签平台制作模板
        $templates = array();
        $template = array();
        // 填充参数  key为参数名称（dataKey），value为填充值
        $fillData = [
            'buyer_address' => $buyer_address,//买家地址
            'buyer_name' => $buyer['realName'],//买家姓名
            'buyer_phone' => $buyer['mobile'],//买家电话
            'buyer_no' => $buyer['idCardNo'],
            'cashpledge' => $order['earnest'],//押金
            'money' => $order['total_price'],//价款
            'num' => $goods['num'].'kg',//数量
            'object' => $goods['title'],//合同标的
            'seller_address' => $seller_address,//卖家地址
            'seller_name' => $seller['realName'],//卖家姓名
            'seller_phone' => $seller['mobile'],//卖家电话
            'seller_no' => $seller['idCardNo'],
            'selltime' => $goods['selltime'],
            'sell_time' => $goods['selltime'],
            'deliverymethod' => $goods['delivery_method'],
            'delivery_method' => $goods['delivery_method'],
            'time' => date('Y-m-d',time()),
        ];
        $template["fillData"] = $fillData;
        // 模板编号
//        $template["templateNo"] = 'TN9835415EEB384CF2AB36B9806342B1E4';
        $template["templateNo"] = 'TNB7CB8E5048CC4820B9153332F35B3105';
        $templates = array($template);
        $contract["templates"] = $templates;
        $result = $asignInstance->createContract($contract, null);
        if($result['rt'] == 1){
            $res = $this->addSigner($contractNo,$order['seller_id'],$order['user_id']);
            //修改订单签署链接
            if($res['rt'] == 1){
                $data = $res['data'];
                db('order')->where('id',$order_id)->update([
                    'signUrl' => $data['signUser'][1]['signUrl'],
                    'signUrl1' => $data['signUser'][0]['signUrl'],
                    'previewUrl' => $data['previewUrl'],
                ]);
                return true;
            }
        }
        return false;
    }

    /**
     * 添加签署方
     */
    public function addSigner($contractNo,$seller_account,$buyer_account)
    {
        $log = Authentication::where('user_id',$seller_account)->where('is_attestation',2)->find();
        $asignInstance = new Acsign();
        $contractUserInput = array();
        $contractUserInput["account"] = $log['serialNo'];//户唯一识别码
        $contractUserInput["contractNo"] = $contractNo;//合同唯一编码
//        $contractUserInput["isNotice"] = 1;

        // 关键字签 签署人1
        $signStrategyKey = array();
        $signStrategyKey["attachNo"] = 1;
        $signStrategyKey["locationMode"] = 4;
        $signStrategyKey["signKey"] = 'seller';
        $signStrategyKey["signType"] = 1;
        $signStrategyList = array($signStrategyKey);
        $contractUserInput["signStrategyList"] = $signStrategyList;
        $contractUserInput["signType"] = 3;
        $contractUserInput["validateType"] = 8;
        $log1 = Authentication::where('user_id',$buyer_account)->where('is_attestation',2)->find();
        // 签署人2
        $contractUserInput2 = array();
        $contractUserInput2["account"] = $log1['serialNo'];
        $contractUserInput2["contractNo"] = $contractNo;
        $contractUserInput2["signType"] = 3;
        $contractUserInput2["validateType"] = 8;

        // 关键字签
        $signStrategyKey2 = array();
        $signStrategyKey2["attachNo"] = 1;
        $signStrategyKey2["locationMode"] = 4;
        $signStrategyKey2["signKey"] = 'buyer';
        $signStrategyList2 = array($signStrategyKey2);
        $contractUserInput2["signStrategyList"] = $signStrategyList2;
        $contractUserList = array($contractUserInput, $contractUserInput2);
        $result = $asignInstance->addSigner($contractUserList);
        return $result;
    }
}
